package org.stephen.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author qiuwenwei
 */
public class HttpRequestUtil {
    /**
     * 发送 GET 请求
     * @param urlStr 请求的 URL
     * @return 响应的字符串
     * @throws Exception 如果请求失败
     */
    public static String doGet(String urlStr,String cookie,String token) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 GET
        connection.setRequestMethod("GET");
        // 设置 Cookie 请求头
        if (cookie != null && !cookie.isEmpty()) {
            connection.setRequestProperty("cookie", cookie);
        }

        // 设置 User-Agent 请求头
        if (token != null && !token.isEmpty()) {
            connection.setRequestProperty("acs-token", token);
        }

        // 获取响应输入流
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    /**
     * 发送 POST 请求
     * @param url 请求的 URL
     * @return 响应的字符串
     * @throws Exception 如果请求失败
     */
    public static String doPost(String url, String json) throws Exception {
        // 创建一个HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost请求对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");

            // 设置请求体
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    // 将响应体转换为字符串并返回
                    return EntityUtils.toString(responseEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果出现异常或响应体为空，返回null
        return null;
    }
}
